﻿using CSharpTestProject.Utils;
using System;
using SeeSharpTools.JY.File;
using System.Windows.Forms;
using System.Text;
using System.Data;
using System.Drawing;

namespace CSharpTestProject.AdminFormFolder
{
    public partial class AddStudentForm : Form
    {
        public _Sql sql;
        public AddStudentForm()
        {
            InitializeComponent();
        }


        private void AddStudentForm_Load(object sender, EventArgs e)
        {
            
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string filePath = "";
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.InitialDirectory = "c:\\";
            ofd.Filter = "Script files (*.csv)|*.csv";
            //ofd.RestoreDirectory = true;
            ofd.Title = ("选择学生表");


            if (ofd.ShowDialog() != DialogResult.OK)
            {
                return; //Not sure if there is supposed to be more here
            }
            filePath = ofd.FileName;
            //方法定义变量
            string[,] data = null;

            //方法里面的调用
            data = CsvHandler.Read<string>(filePath, (long)0, 0, -1, -1, Encoding.UTF8);
            DataTable dt = new DataTable();
            DataRow dr = null;

            for (int i = 0; i < data.GetLength(1); i++)
            {
                dt.Columns.Add(new DataColumn(data[0, i]));
            }
            for (int j = 1; j < data.GetLength(0); j++)
            {
                dr = dt.NewRow();
                for (int k = 0; k < data.GetLength(1); k++)
                {
                    dr[k] = data[j, k];
                }
                dt.Rows.Add(dr);
            }
            //不允许添加行
            dataGridView1.AllowUserToAddRows = false;
            //背景为白色
            dataGridView1.BackgroundColor = Color.White;
            //只允许选中单行
            dataGridView1.MultiSelect = false;
            //整行选中
            dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            dataGridView1.DataSource = dt;

        }

        private void button2_Click(object sender, EventArgs e)
        {
            DataTable dt = dataGridView1.DataSource as DataTable;

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                string s = $"INSERT INTO students (xh,name,bj,kcm,teachr_name)" +
                     $"VALUES ('{dt.Rows[i]["学号"]}','{dt.Rows[i]["姓名"]}','{dt.Rows[i]["班级"]}','{dt.Rows[i][dt.Columns.Count - 2]}','{dt.Rows[i][dt.Columns.Count - 1]}')";
                try
                {
                    sql.ManageData(s);
                }
                catch
                {
                    MessageBox.Show("上传失败！请检查数据是否正确");
                    return;
                }
            }
            MessageBox.Show("上传成功！");
        }
    }
}
